<?php
	defined('_JEXEC') or die();
	jimport('joomla.application.component.model');
	class DivisionModelDivision extends JModel 
	{	   
		function getDivisions()
		{			
			$db = $this->getDBO();
			$sql = "SELECT main_division.division_id AS division_id, ";
			$sql.= "main_division.name AS name, ";
			$sql.= "parent_division.division_id AS parent_division_id, ";
			$sql.= "parent_division.name AS parent_division_name ";
			$sql.= "FROM #__pbny_divisions AS main_division ";
			$sql.= "LEFT OUTER JOIN #__pbny_divisions AS parent_division ";
			$sql.= "ON main_division.parent_division_id = parent_division.division_id";
			
			$db->setQuery($sql);
			$divisions = $db->loadObjectList();
		 
			if ($divisions === null)
				JError::raiseError(500, 'Error reading db');
				
			return $divisions;
		}
		
		function getDivision($id)
		{
			$db = $this->getDBO();
		 
			$db->setQuery('SELECT main_division.division_id AS division_id, main_division.name AS name, parent_division.division_id AS parent_division_id, parent_division.name AS parent_division_name from #__divisions AS main_division LEFT OUTER JOIN #__divisions AS parent_division ON main_division.parent_division_id = parent_division.division_id WHERE main_division.division_id = ' . $id);
			$division = $db->loadObjectList();
		 
			if ($division === null)
				JError::raiseError(500, 'Error reading db');
				
			if(count($division)	> 0)
				return $division[0];
			else 
				return null;
		}
		
        function saveDivision($division)
		{
			$row =& $this->getTable('division');            
           
			if (!$row->bind($division)) 
			{
				JError::raiseError(500, 'Error binding data');              
			}     
       
			if (!$row->check()) 
			{
				JError::raiseError(500, 'Invalid data');                           
			}
       
            if (!$row->store()) 
			{
				$errorMessage = $row->getError();
				JError::raiseError(500, 'Error binding data: '.$errorMessage);                           
			}
		}
		
		function deleteDivisions($ids)
		{
			$query = "DELETE FROM #__divisions WHERE division_id IN (" .implode(',', $ids). ")";
			$db = $this->getDBO();
            $db->setQuery($query);
            if (!$db->query())
			{
                $errorMessage = $this->getDBO()->getErrorMsg();
                JError::raiseError(500, 'Error deleting divisions: '.$errorMessage);  
            }      
		}
	}
?>